<!--
    by: yuanbiao 2020年10月09日
    name: x-back-top
    notes:
-->
<template>
  <div v-show="isShow" :class="prefixCls" :style="styles" @click="clickHandler">
    <slot>
      <div :class="`${prefixCls}__inner`">
        <i class="xvu-iconfont xvu-arrow-up"></i>
      </div>
    </slot>
  </div>
</template>

<script>
import {scrollTop} from '@/script/utils.js'
const prefixCls = 'x-back-top'
export default {
  name: 'x-back-top',
  props: {
    height: {
      type: Number,
      default: 400
    },
    bottom: {
      type: Number,
      default: 30
    },
    right: {
      type: Number,
      default: 30
    },
    duration: {
      type: Number,
      default: 1000
    }
  },
  data() {
    return {
      prefixCls: prefixCls,
      isShow: false
    }
  },
  computed: {
    styles () {
      return {
        bottom: `${this.bottom}px`,
        right: `${this.right}px`
      }
    }
  },
  mounted () {
    window.addEventListener('scroll', this.scrollHandler)
    window.addEventListener('resize', this.scrollHandler)
  },
  beforeDestroy () {
    window.removeEventListener('scroll', this.scrollHandler)
    window.removeEventListener('resize', this.scrollHandler)
  },
  methods: {
    scrollHandler () {
      this.isShow = window.pageYOffset >= this.height
    },
    clickHandler () {
      let from = document.documentElement.scrollTop || document.body.scrollTop
      let to = 0
      scrollTop(window, from, to, this.duration)
      this.$emit('click')
    }
  }
}
</script>
